package com.googlecode.gwt.test.plugin.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IProject;

import com.googlecode.gwt.test.plugin.editors.ProjectPluginProperty;

public class MacroExtractor {
	File directory = null;

	public MacroExtractor(String file) {
		directory = new File(file);
	}

	public List<String> extractMacros(IProject project) {
		List<String> retour = new ArrayList<String>();
		if (directory != null) {
			if (directory.isDirectory()) {
				for (File f : directory.listFiles()) {
					retour.addAll(extractMacros(f,project));
				}
			}
		}
		return retour;
	}

	public List<String> extractMacros(File f,IProject project) {
		List<String> retour = new ArrayList<String>();
		if (f.isFile()) {
			try {
				InputStreamReader reader = new InputStreamReader(new FileInputStream(f));
				BufferedReader r = new BufferedReader(reader);
				String line = null;
				Pattern p = Pattern.compile("macro;(.*)\\s*;?");
				Pattern comment= Pattern.compile("\\s*\\*\\*.*");
				int line_number=1;
				String comments="";
				while ((line = r.readLine()) != null) {
					Matcher commentMatch=comment.matcher(line);
					if(commentMatch.matches()){
						comments+=line+"\n";
					}
					Matcher m = p.matcher(line);
					if (m.matches()) {
						retour.add(m.group(1));
						ProjectPluginProperty.getInstance().getMacroResource(project).addMacro(m.group(1), f);
						ProjectPluginProperty.getInstance().getMacroResource(project).addMacrosLine(m.group(1), line_number);
						ProjectPluginProperty.getInstance().getMacroResource(project).addMacrosComment(m.group(1), comments);
						comments="";
					}
					line_number++;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return retour;
	}

	public MacroExtractor() {
	}

	public MacroExtractor(File file) {
		directory = file;
	}

	public static void main(String[] args) {
		long start = System.nanoTime();
		MacroExtractor extractor = new MacroExtractor("C:/Workspaces/FTSOFT/soft-cu/functionnal-test/macros");
		List<String> res = extractor.extractMacros(null);
		for (String r : res) {
			System.out.print(r + ",");
		}
		System.out.println("\n" + (System.nanoTime() - start));
	}
}
